package com.scujj.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.scujj.pojo.*;
import com.scujj.service.BlogService;
import com.scujj.service.CommentService;
import com.scujj.service.ThumbsUpService;
import com.scujj.service.UserService;
import com.scujj.util.FileUtil;
import com.scujj.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/blog")
@RefreshScope
public class BlogController {

    @Autowired
    UserService userService;

    @Autowired
    BlogService blogService;

    @Autowired
    ThumbsUpService thumbsUpService;

    @Autowired
    CommentService commentService;

    @Value("${staticFilePath}")
    String rootStaticPath;

    @Value("${imgPath.blogMedia}")
    String blogMediaPath;

    @Value("${staticFilePath}" + "${imgPath.blogMedia}")
    String blogMediaFullPath;

    @PostMapping("/publish")
    Result publishBlog(@RequestParam(required = false,name = "context") String context,
                       @RequestHeader HashMap<String,String> header,
                       @RequestParam(value = "images",required = false) MultipartFile[] images,
                       @RequestParam(value = "retransmissionBlogId",required = false) Long retransmissionBlogId){
        // 验证token
        Result result=userService.getUserByToken(header);
        if(result.getCode()==-1){
            return result;
        }
        User user = ResultUtil.singleTrans(result.getData(),User.class);
        if(context==null){
            return Result.error("内容不能为空");
        }
        String imgPath=FileUtil.uploadFiles(rootStaticPath,blogMediaPath,images);
        blogService.publishBlog(user.getId(),context, imgPath,retransmissionBlogId);
        return Result.success();
    }

    @GetMapping("/last")
    Result lastBlog(@RequestParam(value = "page",defaultValue = "1") int page,@RequestParam(value = "number",defaultValue = "5") int number){
        if(page<1){
            return Result.error("页数错误");
        }
        if(number<1){
            return Result.error("每页数量错误");
        }
        List<Blog> list=blogService.lastBlogList(page,number);
        return Result.success(list);
    }

    @GetMapping("/hot")
    Result hotBlog(@RequestParam(value = "page",defaultValue = "1") int page,@RequestParam(value = "number",defaultValue = "5") int number){
        if(page<1){
            return Result.error("页数错误");
        }
        if(number<1){
            return Result.error("每页数量错误");
        }

        List<Blog> list=blogService.hotBlogList(page,number);
        return Result.success(list);
    }

    @GetMapping("/subscribe_blog_list")
    Result subscribeBlog(@RequestParam(value = "page",defaultValue = "1") int page,@RequestParam(value = "number",defaultValue = "5") int number, @RequestHeader HashMap<String,String> header){
        if(page<1){
            return Result.error("页数错误");
        }
        if(number<1){
            return Result.error("每页数量错误");
        }
        Result result=userService.getUserByToken(header);
        if(result.getCode()==-1){
            return result;
        }
        User user = ResultUtil.singleTrans(result.getData(),User.class);
        List<Blog> list=blogService.subscribeBlogList(page,number,user.getId());
        return Result.success(list);
    }


    @GetMapping("/user_blog")
    Result getBlogListByUserId(@RequestParam(value = "id",defaultValue = "0") long id,@RequestParam(value = "limit",defaultValue = "0") int limit,@RequestParam(value = "page",defaultValue = "0") int page){
        QueryWrapper<Blog> queryWrapper=new QueryWrapper<>();
        if(id==0){
            return Result.error();
        }
        if(limit<1||page<1){
            return Result.error("参数有误");
        }
        queryWrapper.eq("uid",id);
        Page<Blog> pageObj=new Page<>(page,limit);
        blogService.page(pageObj,queryWrapper);
        List<Blog> blogList = pageObj.getRecords();
        blogList.forEach(blog -> {
            QueryWrapper<CommentBlog> commentWrapper = new QueryWrapper<>();
            commentWrapper.eq("bid",blog.getId());
            List<CommentBlog> commentList = commentService.list(commentWrapper);

            QueryWrapper<BlogThumbsUpNum> thumbsUWrapper=new QueryWrapper<>();
            thumbsUWrapper.eq("bid",blog.getId());
            thumbsUWrapper.eq("uid",id);
            List<BlogThumbsUpNum> thumbUpList = thumbsUpService.list(thumbsUWrapper);

            List<User> thumbUpUserList = new LinkedList<>();
            thumbUpList.forEach(blogThumbsUp -> {
                thumbUpUserList.add(new User().setId(blogThumbsUp.getUid()));
            });
            blog.setThumbsUpUserList(thumbUpUserList);
            blog.setCommentBlogList(commentList);
        });

        Long total = pageObj.getTotal();
        HashMap<String,Object> resultMap=new HashMap<>();
        resultMap.put("blogList",blogService.blogListSet(blogList));
        resultMap.put("total",total);
        return Result.success(resultMap);
    }


    @GetMapping("/del")
    Result delABlog(@RequestParam(value = "id",defaultValue = "0") long id,@RequestHeader HashMap<String,String> header){
        Result result=userService.getUserByToken(header);
        if(result.getCode()==-1){
            return result;
        }
        User user = ResultUtil.singleTrans(result.getData(),User.class);
        Blog blog=blogService.getById(id);
        if(!Objects.equals(user.getId(), blog.getUid())){
            return Result.error("你没有删除此帖子的权限");
        }
        blogService.delBlog(id);
        return Result.success("删除成功");
    }

    @GetMapping("/count")
    Result CountBlogs(@RequestHeader HashMap<String,String> header){
        Result result=userService.getUserByToken(header);
        if(result.getCode()==-1){
            return result;
        }
        User user = ResultUtil.singleTrans(result.getData(),User.class);
        QueryWrapper<Blog> wrapper=new QueryWrapper<Blog>();
        wrapper.eq("uid",user.getId());
        long num = blogService.count(wrapper);
        return Result.success(num);
    }

    @GetMapping("/countById")
    Result CountBlogsById(@RequestParam("id") String id, @RequestHeader HashMap<String,String> header){
        QueryWrapper<Blog> wrapper=new QueryWrapper<Blog>();
        wrapper.eq("uid",id);
        long num = blogService.count(wrapper);
        return Result.success(num);
    }
}
